package userHelp

import (
	myConfig "common/config"
	"common/helper"
	"encoding/json"
	"fmt"
	"math/rand"
	"sort"
	"time"
)

/*
计算此笔订单隐藏的金额
*/

type CfgChargeHiddenItem struct {
	Amount      int `json:"Amount" db:"Amount" cbor:"Amount"`
	TriggerRate int `json:"TriggerRate" db:"TriggerRate" cbor:"TriggerRate"`
	HiddenType  int `json:"HiddenType" db:"HiddenType" cbor:"HiddenType"` //1  按比例隐藏 2按固定值隐藏
	HiddenParam int `json:"HiddenParam" db:"HiddenParam" cbor:"HiddenParam"`
}

type CfgChargeHiddenSlice []CfgChargeHiddenItem

func (p CfgChargeHiddenSlice) Len() int           { return len(p) }
func (p CfgChargeHiddenSlice) Less(i, j int) bool { return p[i].Amount > p[j].Amount }
func (p CfgChargeHiddenSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }

func GetChargeHiddenMount(uid string, OrderAmount int, chargeType int) int {
	var JsonContent string
	var SqlSelect string

	//先取自己的配置
	if G_UserButton.GetChargeHiddenButton(uid) == 1 {
		if chargeType == 1 && G_UserButton.GetChargeHiddenSwitchS(uid) == 1 {
			JsonContent = G_UserButton.GetChargeHiddenControlS(uid)
		}

		if chargeType == 2 && G_UserButton.GetChargeHiddenSwitchF(uid) == 1 {
			JsonContent = G_UserButton.GetChargeHiddenControlF(uid)
		}
	}

	BusiId := GetMemberBusinessId(uid)
	if len(JsonContent) <= 2 && BusiId != "0" && myConfig.GetGameCfgInt(myConfig.CfgAllowBusiChargeHidden) == 1 {
		SqlSelect = fmt.Sprintf("select json_content from tbl_cfg_sys_gradient where business_id=%s and switch = 1 and type=%d", BusiId, chargeType)
		// busi
		g_sql.Get(&JsonContent, SqlSelect)
	}

	//channel
	if len(JsonContent) <= 2 && myConfig.GetGameCfgInt(myConfig.CfgAllowChannelChargeHidden) == 1 {
		OptId := GetMemberOperatorId(uid)
		SqlSelect = fmt.Sprintf("select json_content from tbl_cfg_sys_gradient where operator_id=%s and switch = 1 and type=%d", OptId, chargeType)
		g_sql.Get(&JsonContent, SqlSelect)
	}

	//offical
	if len(JsonContent) <= 2 {
		SqlSelect = fmt.Sprintf("select json_content from tbl_cfg_sys_gradient where operator_id=888888 and switch = 1 and type=%d", chargeType)
		g_sql.Get(&JsonContent, SqlSelect)
	}

	if len(JsonContent) <= 2 {
		return 0
	}

	var CfgChargeHiddenLst CfgChargeHiddenSlice
	err := json.Unmarshal([]byte(JsonContent), &CfgChargeHiddenLst)
	if err != nil {
		helper.SqlErrLog("Hidden Charge cfg:%s", JsonContent)
		return 0
	}

	var HiddenAmount int = 0
	sort.Stable(CfgChargeHiddenLst)
	for _, cfgItem := range CfgChargeHiddenLst {
		if OrderAmount >= cfgItem.Amount {
			rand.New(rand.NewSource(time.Now().UnixNano()))
			randValue := rand.Intn(100)
			if cfgItem.TriggerRate > randValue {
				//触发订单隐藏概率
				if cfgItem.HiddenType == 1 {
					HiddenAmount = cfgItem.HiddenParam * OrderAmount / 100
				} else {
					HiddenAmount = cfgItem.HiddenParam
				}
			}
			break
		}
	}

	if HiddenAmount >= OrderAmount {
		HiddenAmount = OrderAmount
	}

	return HiddenAmount
}
